package com.itheima.dubbo.handler;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class MyHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        sendFill(metaObject, Arrays.asList(FieldFill.INSERT, FieldFill.INSERT_UPDATE));
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        sendFill(metaObject, Arrays.asList(FieldFill.UPDATE, FieldFill.INSERT_UPDATE));
    }

    public void sendFill(MetaObject metaObject, List<FieldFill> fillList) {
        //获取metaObject父类
        Object originalObject = metaObject.getOriginalObject();
        //通过反射获取所有的成员变量
        Field[] fields = originalObject.getClass().getDeclaredFields();
        //添加到集合中
        List<Field> list = Arrays.asList(fields);
        //创建一个map集合来保存键值
        Map<String, Class> maps = new HashMap<>();
        //遍历参数集合
        for (Field field : fields) {
            TableField annotation = field.getAnnotation(TableField.class);
            if (annotation == null) {
                continue;
            }
            //获取注解属性
            FieldFill fill = annotation.fill();
            if (fill == null) {
                continue;
            }
            //遍历参数集合
            for (FieldFill fieldFill : fillList) {
                //判断注解的属性名是否等于参数里面的集合
                if (fieldFill.name().equals(fill.name())) {
                    //添加到map集合中
                    maps.put(field.getName(), field.getType());
                }
            }
        }
        //遍历map集合
        maps.forEach((key, value) -> {
            //获取字段的值的类型
            //进行复制
            if (value == LocalDateTime.class) {
                metaObject.setValue(key, LocalDateTime.now());
            } else if (value == LocalDate.class) {
                metaObject.setValue(key, LocalDate.now());
            }
        });
    }
}
